package com.ruoyi.framework.web.service;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.cache.CacheUtils;
import net.oschina.j2cache.CacheChannel.Region;
import net.oschina.j2cache.CacheObject;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @description:
 * @author: wenchao
 * @date: 2019-11-16
 */
@Service("cache")
public class CacheService {

    /**
     * 获取缓存列表
     *
     * @return
     */
    public Collection<Region> getCacheNameList() {
        return CacheUtils.regions();
    }

    /**
     * 根据缓存名称 获取所有key
     *
     * @param cacheName
     * @return
     */
    public List<Map<String, String>> getCacheKeyList(String cacheName) {
        List<Map<String, String>> results = new ArrayList<>();
        if (StringUtils.isEmpty(cacheName)) {
            return results;
        }
        Set<String> set = CacheUtils.keys(cacheName);
        set.forEach(key -> {
            Map<String, String> map = new HashMap<>(1);
            map.put("id", key);
            results.add(map);
        });
        return results;
    }

    /**
     * 根据缓存key 获取缓存值
     *
     * @param cacheName
     * @param key
     * @return
     */
    public CacheObject getCacheValue(String cacheName, String key) {
        return CacheUtils.getCacheObject(cacheName, key);
    }

    /**
     * 根据缓存 key 清除缓存
     *
     * @param cacheName
     * @param key
     */
    public void clearCache(String cacheName, String key) {
        if (StringUtils.isEmpty(cacheName)) {
            Collection<Region> regions = getCacheNameList();
            if (CollectionUtils.isEmpty(regions)) {
                return;
            }
            regions.forEach(region -> CacheUtils.clear(region.getName()));
        } else if (StringUtils.isEmpty(key)) {
            CacheUtils.clear(cacheName);
        } else {
            CacheUtils.remove(cacheName, key);
        }
    }
}
